<template>
  <div>
    <div style="margin-bottom: 20px; max-width: 880px" ref="editor"></div>
  </div>
</template>

<script>
import WangEditor from "wangeditor";
import AlertMenu from "./editor.js";
export default {
  name: "editor",
  props: ["text", "editorProp"],
  setup(props, { emit }) {
    const editor = ref(null);
    let instance;
    const setVal = (val) => {
      instance.txt.html(val);
    };
    onMounted(() => {
      instance = new WangEditor(editor.value);
      instance.menus.extend("alertMenu", AlertMenu); // 配置扩展的菜单
      instance.config.menus = instance.config.menus.concat("alertMenu");
      instance.config.onchange = (html) => {
        instance.txt.html(html);
      };
      setTimeout(() => {
        if (props.text) instance.txt.html(props.text);
      }, 800);
      instance.config.uploadImgServer = "https://files.liuliangbang.vip/pic/ups";
      instance.config.uploadImgHooks = {
        // 图片上传并返回了结果，图片插入已成功
        success: function (xhr) {
          console.log("success", xhr);
        },
        // 图片上传并返回了结果，但图片插入时出错了
        fail: function (xhr, editor, resData) {
          console.log("fail", resData);
        },
        // 上传图片出错，一般为 http 请求的错误
        error: function (xhr, editor, resData) {
          console.log("error", xhr, resData);
        },
        // 上传图片超时
        timeout: function () {
          console.log("timeout");
        },
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function (insertImgFn, result) {
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          let arr = result.value.saved;
          if (arr.length > 0) {
            arr.map((item) => {
              insertImgFn(item.info.cdnUrl);
            });
          } else {
            ElMessage.error("上传失败");
          }
        }
      };
      instance.config.zIndex = 1;
      instance.config.onchange = function (newHtml) {
        emit("getEditorValue", newHtml, props.editorProp);
      };
      instance.create();
    });
    // watch(() => props.text,(val) => {
    //   instance.txt.html(val)
    // })
    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    });
    return {
      editor,
      setVal
    };
  }
};
</script>

<style></style>
